<?php
/**
 * Created by PhpStorm.
 * User: lih
 * Date: 2017/11/26
 * Time: 22:05
 */
namespace common\libs\dsyog\util;

use Yii;

class UploadMan
{
    public $targetPath;

    public function initParams()
    {
        $pathWebRoot = Yii::getAlias('@webroot');
        $this->targetPath = $this->concatPath($pathWebRoot, 'assets/upload/image');
    }

    public function storageUploadByPath($filePath)
    {
        $fileSuffix = $this->getFilSuffix($filePath);
        $newFileName = $this->createGuid() . $fileSuffix;
        $newFileName = $this->concatPath($this->targetPath, $newFileName);
        rename($filePath, $newFileName);
    }

    public function getFilSuffix($filePath)
    {
        preg_match('/(\.\w+)$/', $filePath, $matches);
        return isset($matches[1]) ? $matches[1] : '';
    }

    public function concatPath($pathHead, $pathTail)
    {
        if(strrchr($pathHead, '/') !== '/') {
            $pathHead = $pathHead . '/';
        }
        if(0 === strpos($pathTail, '/')) {
            $pathTail = substr($pathTail, 1);
        }
        return $pathHead . $pathTail;
    }

    public function createGuid() {
        /**
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12);
         */
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        return $charid;
    }
}
